package org.brisling.authorize.shiro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.brisling.base.domain.RetDomain;
import org.brisling.common.SysConfig;
import org.brisling.common.util.JsonUtil;
import org.brisling.sysman.domain.Users;



public class SSOService {

	private final static String  SSO_URL ="http://192.168.0.20:8080/api/protal?userid=%1$s&pwd=%2$s";
	
	private final static int connectionTimeout=50;
	private static SSOService service;
	private SSOService(){}
	
	public static SSOService getService(){
		if(service==null)
			service = new SSOService();
		return service;
	}
	
	@SuppressWarnings("unchecked")
	public static String getSSOPwd(String uid,String pwd){
		if((uid!=null)&&(uid.trim().compareTo("admin")==0)){
			return "success";
		}
		String SSO_url =String.format(SSO_URL,uid,pwd);//获取用户认证的帐号URL
   	    System.out.println("URL: "+SSO_url);
   	    URL url;
   	    HttpURLConnection connection;
   	    StringBuilder json = new StringBuilder();
   		try {
   			url = new URL(SSO_url);
   			connection = (HttpURLConnection) url.openConnection();
   			connection.setConnectTimeout(connectionTimeout);
   	        connection.connect();
   	        
   	        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
               String inputLine = null;  
               while ( (inputLine = in.readLine()) != null) {  
                   json.append(inputLine);  
               }  
               in.close(); 
   	        System.out.println("response:"+ json.toString());
   		} catch (MalformedURLException e) {
   			// TODO Auto-generated catch block
   			System.out.println("MalformedURLException occurred !!!");
   		} catch (IOException e) {
   			// TODO Auto-generated catch block
   			System.out.println("IOException occurred !!!");
   		}
   		
   		if((json!=null)&&(json.length()>0)){
   			Map<String,Object> map = JsonUtil.bodyToObj(json.toString(), Map.class);
   			return map.get("status").toString();
   		}
   		return "false";
   		
	}
	
	public static String loginCheck(String uid,String pwd){
		
//	     String SSO_url =String.format("http://192.168.0.20/login/check?userid=%1$s&password=%2$s",uid,pwd);//获取用户认证的帐号URL
//	     String SSO_url ="http://192.168.0.20/login/check";//获取用户认证的帐号URL
	     String SSO_url ="http://192.168.0.20:8080/api/protal";//获取用户认证的帐号URL
	     System.out.println("URL: "+SSO_url);
	     URL url;
	     HttpURLConnection connection;
	    
	     String sessionId = null;
		try {
			
			String _param = String.format("userid=%1$s&pwd=%2$s", uid,pwd);
			_param=StringUtils.toEncodedString(_param.getBytes(), Charset.forName("UTF-8"));
			SSO_url = SSO_url +"?"+ _param;
			url = new URL(SSO_url);
			
			
			connection = (HttpURLConnection) url.openConnection();
			
//			connection.setRequestMethod("POST");
			
			//是否输入参数
//			connection.setDoOutput(true);
			
//			connection.getOutputStream().write(_param.getBytes());
			connection.setConnectTimeout(connectionTimeout);
	        connection.connect();
	        
	        System.out.println("sessionId: "+sessionId);
	        String sid=getResponStream(connection.getInputStream());
	        if(sid!=null){
	        	if(sid.indexOf("success")>=0){
	        		sessionId = "success";
	        	}
	        	
//		        String cookieValue=connection.getHeaderField("Set-Cookie");
//		        if(cookieValue!=null)
//		        	sessionId=cookieValue.substring(0, cookieValue.indexOf(";"));
//		        
//		        System.out.println("cookie value:"+cookieValue);
	        }            
	        
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sessionId;
		
	}
	
	private static String getResponStream(InputStream is) throws IOException{
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		String inputLine = null;
		StringBuilder json = new StringBuilder();
		while ( (inputLine = in.readLine()) != null) {  
            json.append(inputLine);  
        }      
		in.close();
		
		String retStr = json.toString();
		if(retStr!=null&&retStr.length()>0){
			return retStr;
		}
		System.out.println("response:"+ retStr);
		return null;
        
	}
	
	
	/**
	 * 验证密码
	 * @param uid
	 * @param plainPwd
	 * @param encryptPwd
	 * @return
	 */
	public static RetDomain verifyPassword(String uid,String plainPwd,String encryptPwd){
		
		RetDomain rd = new RetDomain();	
		
		//获取密码验证方式定义
		String type = SysConfig.getConfig("verifyPassword");
		
		//默认密码验证模式定义
		String _type = type ==null?"md5":type;
		
		//判断密码验证模式
		switch(_type){
			case "md5":				
				//使用单点登录md5
				rd = verifyMD5(uid,plainPwd,encryptPwd);				
				break;
			case "asc":
				rd = verifyASC(uid,plainPwd,encryptPwd);
				break;
			case "plain":
				rd = verifyPlainText(uid,plainPwd,encryptPwd);
				break;
			default:
					rd = verifyMD5(uid,plainPwd,encryptPwd);
		}
		
		return rd;
	}
	/*
	 * 验证用户单点登录md5密码
	 * @param uid
	 * @param pwd
	 * @return
	 */
	private static RetDomain verifyMD5(String uid,String plainPwd,String encryptPwd){
		
		RetDomain rd = new RetDomain();
		if(uid==null || plainPwd==null || encryptPwd==null){
			rd.setErrorMsg("param error");
			return rd;
		}
		
		String _generatePwd = PasswordSecurity.generateMD5(uid,plainPwd,true);
		
		if(_generatePwd!=null){
			if(_generatePwd.trim().compareTo(encryptPwd.trim())==0){
				rd.setSuccessMsg("success");
			}
		}
		return rd;
	}
	
	/*
	 * 验证用户本地md5密码
	 * @param uid
	 * @param pwd
	 * @return
	 */
	public static RetDomain verifyLocalMD5(Users user,String plainPwd,String encryptPwd){
		
		RetDomain rd = new RetDomain();
		if(user==null || plainPwd==null || encryptPwd==null){
			rd.setErrorMsg("param error");
			return rd;
		}
		
		if(PasswordSecurity.authenticPassword(user, plainPwd)){		
			rd.setSuccessMsg("success");			
		}
		return rd;
	}
	
	/**
	 * 验证用户ASC密码
	 * @param uid
	 * @param pwd
	 * @return
	 */
	private static RetDomain verifyASC(String uid,String plainPwd,String encryptPwd){
		
		RetDomain rd = new RetDomain();
		if(uid==null || plainPwd==null || encryptPwd==null){
			rd.setErrorMsg("param error");
			return rd;
		}
		
		String _generatePwd = PasswordSecurity.generateASC(uid,plainPwd,false);
		
		if(_generatePwd!=null){
			if(_generatePwd.trim().compareTo(encryptPwd.trim())==0){
				rd.setSuccessMsg("success");
			}
		}
		return rd;
	}
	
	/**
	 * 验证用户明文密码
	 * @param uid
	 * @param pwd
	 * @return
	 */
	private static RetDomain verifyPlainText(String uid,String plainPwd,String encryptPwd){
		
		RetDomain rd = new RetDomain();
		if(uid==null){
			rd.setErrorMsg("param error");
			return rd;
		}
		
		//处理密码为空情况
		plainPwd=plainPwd==null?"":plainPwd.trim();
		encryptPwd=encryptPwd==null?"":encryptPwd.trim();
		
		if(plainPwd.compareTo(encryptPwd)==0){
			rd.setSuccessMsg("success");
		}
		
		return rd;
	}
}
